import { writeFileSync } from "node:fs";

export type PageParams = {
  page: number;
  pageSize: number;
  dirId: string; // 文件夹ID
  stoken?: string; // 校验码ID
  pwd_id?: string; // 凭证字符
  deep?: boolean; // 深度遍历
  sort?: string;
  showDir?: boolean; // 展示每级文件夹名称
  onlyDir?: boolean; // 只展示文件夹，不展示文件
  maxDir?: number; // 最大文件夹深度
  delay?: number; // 延迟时间
};
export type FileItem = {
  file_name: string;
  file?: boolean; // 是否是文件
  dir?: boolean; // 是否是文件夹
  fid?: string; // 下级文件夹或文件id
};
export type ResultData = {
  status: number;
  code: number;
  message: string;
  timestamp: number;
  data: {
    is_owner: number;
    list: FileItem[];
  };
  metadata: {
    _size: number;
    _page: number;
    _count: number;
    _total: number;
    check_fid_token: number;
    _g_group: string;
    _t_group: string;
  };
};

export const getDefaultParams = (params: PageParams) => {
  const {
    page,
    pageSize,
    dirId,
    pwd_id,
    stoken,
    sort = "file_type:asc,updated_at:desc",
  } = params;
  return `pr=ucpro&fr=pc&uc_param_str=&pwd_id=${pwd_id}&stoken=${getEncodeURIComponent(
    stoken
  )}&pdir_fid=${dirId}&force=0&_page=${page}&_size=${pageSize}&_fetch_banner=0&_fetch_share=0&_fetch_total=1&_sort=${sort}&__dt=68577&__t=${new Date().getTime()}`;
};

export const getDefaultHeaders = (opts: HeadersInit) => {
  return {
    accept: "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,ru;q=0.7,nl;q=0.6",
    priority: "u=1, i",
    "sec-ch-ua":
      '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"Windows"',
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-site",
    Referer: "https://pan.quark.cn/",
    "Referrer-Policy": "strict-origin-when-cross-origin",
    ...opts,
  };
};

export const saveFile = (chunk: string, filename: string) => {
  writeFileSync(filename, chunk);
};

// 转义字符串
const getEncodeURIComponent = (str: string) => encodeURIComponent(str);
